/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQml.Models 2.12
import QtQml 2.12
import QtGraphicalEffects 1.12
import QtQuick.Controls 2.12
import org.ukui.tablet 1.0
import "createUninstallDialog.js" as UninstallJs
import "groupController.js" as GroupPageController
import org.ukui.qqc2style.private 1.0 as StylePrivate
import "./baseComponent"
import "."

Rectangle {
    id: taskBar
    property var parentChange
    property int listviewY: 904 * Style.tabletScaleFactor
    property bool replayAllowed: false
    property bool updateData: false //relese时是否更新数据库
    property bool singleWindow: false

    signal taskbarItemEnterDesktop()
    signal taskbarItemEnterTaskbar()
    signal groupItemEnterDesktop()
    property bool taskbarReplayAllowed: false

    property string iconPromptBox
    property string textPromptBox
    property string tarDesktopName
    property int groupId: 0
    property bool isTaskbarAppLeaveTaskbar: false

    width: taskbarBackground.width + 4 + 2 * Style.tabletScaleFactor
    height: 96 * Style.tabletScaleFactor + 4 + 2 * Style.tabletScaleFactor
    visible: true
    clip: false
    color: "transparent"
    layer.enabled: openGLEnabled
    layer.effect: DropShadow {
        source: taskBar
        color: "#737373"
        opacity: 0.25
        radius: 4.0
    }
    state: "Normal"

    states: [
        State {
            name: "Normal"
        },
        State {
            name: "Show"
            PropertyChanges {
                target: taskBar
                y: 0
            }
        },
        State {
            name: "Hide"
            PropertyChanges {
                target: taskBar
                y: taskBar.height * 2
            }
        }
    ]
    transitions: Transition {
        ParallelAnimation {
            NumberAnimation { target: taskBar; properties: "x,y"; duration: 200 }
        }
    }

    DropArea {
        height: (96 + 96/2) * Style.tabletScaleFactor
        anchors.centerIn: parent
        width: taskbarBackground.width
        visible: !GroupController.groupPopuped
        onEntered:  {
            console.log("DropArea onEntered")
            if (drag.source.groupId === 0) {
                isTaskbarAppLeaveTaskbar = false;
            }
            if(listview.count < 6 && drag.source.groupId !== 0 && drag.source.type === 1 &&
                    !GroupController.groupPopuped) {
                replayAllowed = true
                modelManager.addPlaceholderItem(listview.count,0,1,1,0)
            }
            if(drag.source.groupId === 0 && !drag.source.appOpen) {
                taskbarItemEnterTaskbar()
            }
        }
        onExited: {
            console.log("DropArea onExited")
            replayAllowed = false
            if (drag.source.groupId === 0) {
                isTaskbarAppLeaveTaskbar = true;
            }
            if (drag.source.mouseReleased) {
                isTaskbarAppLeaveTaskbar = false;
                drag.source.mouseReleased = false;
                return
            }
            modelManager.removePlaceholderItem()
            if(drag.source.groupId === 0 && !drag.source.appOpen) {
                taskbarItemEnterDesktop()
            }
            if(drag.source.groupId > 0 && !GroupController.groupPopuped) {
                groupItemEnterDesktop()
            }
        }

        Rectangle {
            id: taskbarBackground
            width: listview.width + 186 * Style.tabletScaleFactor//245
            height: 96 * Style.tabletScaleFactor
            radius: 24 * Style.tabletScaleFactor
            color: StylePrivate.StyleHelper.basecolorrole
            opacity: 0.85
            anchors.centerIn: singleWindow ? undefined : parent
            anchors.top: singleWindow ? parent.top : undefined
            anchors.topMargin: 5 * Style.tabletScaleFactor
        }

        ListView {
            id: listview
            anchors.left: taskbarBackground.left
            anchors.leftMargin: 2.5 * Style.tabletScaleFactor
            anchors.verticalCenter: taskbarBackground.verticalCenter
            width: {
                if(listview.count <= 6) {
                    return 534 * Style.tabletScaleFactor
                }
                if (listview.count > 6 && listview.count <= 9) {
                    return listview.count * 89 * Style.tabletScaleFactor
                }
                if(listview.count > 9 && listview.count <= 15) {
                    return Screen.width > Screen.height ?
                                listview.count * 89 * Style.tabletScaleFactor :
                                (9 * 89 + 37) * Style.tabletScaleFactor
                }
                if(listview.count > 15) {
                    return Screen.width > Screen.height ?
                                (1335 +37) * Style.tabletScaleFactor :
                                (9 * 89 + 37) * Style.tabletScaleFactor
                }
            }
            height: taskbarBackground.height
            clip: true
            orientation: ListView.Horizontal
            addDisplaced: Transition { NumberAnimation { properties: "x,y"; duration: 200 } }
            move: Transition { NumberAnimation { properties: "x,y"; duration: 200 } }
            moveDisplaced: Transition { NumberAnimation { properties: "x,y"; duration: 200 } }
            remove: Transition { NumberAnimation { properties: "x,y"; duration: 200 } }
            removeDisplaced: Transition { NumberAnimation { properties: "x,y"; duration: 200 } }
            displaced: Transition { NumberAnimation { properties: "x,y"; duration: 200 } }
            model: modelManager.taskbarModel
            delegate: listviewDelegate
//            highlightRangeMode: ListView.StrictlyEnforceRange;//切换item的时候currentIndex也跟随着变化
            onMovementStarted: {
                if(listview.count > 15) {
                    leftmask.visible = true
                    rightmask.visible = true
                }
            }
            onMovementEnded: {
                if(listview.count > 15) {
                    leftmask.visible = listview.contentX > 0 ? true : false
                    rightmask.visible = listview.atXEnd ? false : true
                }
            }
            onCountChanged: {
                if(listview.count <= 15) {
                    rightmask.visible = false
                    leftmask.visible = false
                }
                else {
                    leftmask.visible = listview.contentX > 0 ? true : false
                    rightmask.visible = listview.atXEnd ? false : true
                }
            }
        }

        Component {
            id: listviewDelegate

            DropArea {
                id: droparea

                property int visualIndex: index
                property int type: 1
                Binding { target: iconback; property: "visualIndex"; value: visualIndex }

                width: 89 * Style.tabletScaleFactor
                height: taskbarBackground.height
                anchors.verticalCenter: parent.verticalCenter

                onEntered: {
                    updateData = true
                    console.log("taskbar onentered", drag.source.groupId, visualIndex, drag.source.type, type)
                    if(visualIndex < 0 || drag.source.type !== type || GroupController.groupPopuped) {
                        return
                    } else {
                        if (drag.source.groupId !== groupId && drag.source.groupId !== undefined) {
                            modelManager.addPlaceholderItem(visualIndex,0,1,1,0)
                            replayAllowed = true
                        } else {
                            modelManager.moveItem(drag.source.visualIndex, visualIndex, 0, 0)
                            modelManager.removePlaceholderItem();
                        }
                    }
                }
                MouseArea {
                    id: dragMousearea
                    anchors.fill: parent
                    onClicked: {
                        modelManager.setAllItemsState(LauncherItem.Normal)
                        iconbackMousearea.Drag.active = false
                        iconbackMousearea.drag.target = null
                        dumpInfoBox.visible = false
                    }
                }
                Rectangle {
                    id: iconback
                    property int visualIndex: 0
                    property int pageIndex: 0
                    property int rowSpan: 1
                    property int columnSpan: 1
                    property bool canMove: false
                    property int type: 1
                    property bool mouseReleased: false
                    property int groupId: 0//taskbar.groupId
                    property bool appOpen: modelData.appOpen
                    property int itemId: modelData.id

                    width: appicon.width
                    height: droparea.height
                    color: "transparent"
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.verticalCenter: parent.verticalCenter

                    Drag.active: iconbackMousearea.drag.active
                    Drag.source: iconback
                    Drag.hotSpot.x: iconback.width/2
                    Drag.hotSpot.y: iconback.height/2

                    states: [
                        State {
                            when: iconback.Drag.active
                            ParentChange {
                                target: iconback
                                parent: topLayer
                            }
                            AnchorChanges {
                                target: iconback
                                anchors.horizontalCenter: undefined
                                anchors.verticalCenter: undefined
                            }
                            PropertyChanges {
                                target: appicon
                                containerState: LauncherItem.Dragging
                            }
                            PropertyChanges {
                                target: openindicator
                                visible: false
                            }
                        }
                    ]
                    MouseArea {
                        id: iconbackMousearea
                        anchors.fill: parent
                        hoverEnabled: false
                        pressAndHoldInterval: modelData.state === LauncherItem.Editable ? 100 : undefined
                        property bool isChangeContainerPage: false

                        Timer {
                            id: changeContainerPageTimer
                            interval: 600
                            onTriggered: {
                                iconbackMousearea.isChangeContainerPage = true
                            }
                        }
                        Timer {
                            id: itemToDesktopTimer
                            interval: 600
                            onTriggered: {
                                GroupController.minimizeGroup()
                            }
                        }

                        onPressAndHold: {
                            if (singleWindow) {
                                return;
                            }
                            iconback.canMove = true
                            iconbackMousearea.drag.target = iconback
                            iconbackMousearea.Drag.active = true
                            modelManager.setAllItemsState(LauncherItem.Editable)
                        }
                        onClicked: {
                            if(modelData.appOpen && modelData.windowId !== -1 && !LauncherItem.Editable) {
                                modelManager.activeWindow(modelData.windowId)
                            }
                            else {
                                if(modelData.state === LauncherItem.Normal){
                                    appManager.runApplication(modelData.desktopFile)
                                }
                            }
                        }
                        onReleased: {
                            isTaskbarAppLeaveTaskbar = false
                            iconback.mouseReleased = true
                            appicon.width = Qt.binding(function() { return 64 * Style.tabletScaleFactor} )
                            appicon.height = Qt.binding(function() { return 64 * Style.tabletScaleFactor} )

                            var itemPos = iconback.mapToItem(null,0,0)
                            if(taskbarReplayAllowed) {
                                if (modelManager.replacePlaceholderItemTaskbar(index,0,0)) {
                                    appicon.visible = false
                                }
                                taskbarReplayAllowed = false
                            } else if (GroupController.aboutToInsertGroup) {
                                GroupController.insertItemToGroup(iconback.visualIndex, iconback.pageIndex,
                                                                  modelData.id, appicon, modelData.name)
                            } else {
                                modelManager.removePlaceholderItem()
                            }

                            iconbackMousearea.Drag.active = false
                            iconbackMousearea.drag.target = null
                            iconback.canMove = false
                            if(updateData) {
                                modelManager.updateCachedData(-1)
                                modelManager.updateCachedData(0)
                                updateData = false
                            }
                        }
                        onPositionChanged: {
                            var itemPos = iconback.mapToItem(null,0,0)
                            if (isTaskbarAppLeaveTaskbar) {
                                appicon.width = 96 * Style.tabletScaleFactor
                                appicon.height = 96 * Style.tabletScaleFactor
                            }
                            else {
                                appicon.width = 64 * Style.tabletScaleFactor
                                appicon.height = 64 * Style.tabletScaleFactor
                            }
                            GroupPageController.taskbarItemPositionChanged(appicon, changeContainerPageTimer,
                                                                         iconbackMousearea, itemToDesktopTimer,
                                                                         GroupController.groupContainer,
                                                                         GroupController.groupContainerId,
                                                                         GroupController.groupPopuped)
                        }
                        onPressed: iconback.mouseReleased = false
                    }
                    AppIconContainer {
                        id: appicon
                        width: 64 * Style.tabletScaleFactor
                        height: 64 * Style.tabletScaleFactor
                        rootItem: parent
                        anchors.centerIn: parent
                        dropShadowOffset: 2
                        opacity: {
                            if (modelData.type === LauncherItem.AppIcon) {
                                if (iconback.canMove) {
                                    return 1
                                }
                                if (iconbackMousearea.pressed) {
                                    return 0.5
                                }
                            }
                            return 1
                        }
                        icon: {
                            switch (modelData.type) {
                            case LauncherItem.AppIcon:
                            case LauncherItem.WindowIcon:
                                return "image://icons/" + modelData.icon
                            default: return ""
                            }
                        }
                        containerState: modelData.state
                        deleteIconWidth: 28
                        onDeleteIconSig: {
                            UninstallJs.createUnInstallDialog(rootWindow, modelData.desktopFile, modelData.name, modelData.icon)
                            taskbar.textPromptBox = model.modelData.name
                            taskbar.iconPromptBox = modelData.icon
                        }
                    }

                    Rectangle {
                        id: openindicator
                        width: 22
                        height: 4 * Style.tabletScaleFactor
                        radius: 2
                        visible: modelData.appOpen
                        anchors.bottom: parent.bottom
                        anchors.bottomMargin: 4 * Style.tabletScaleFactor
                        anchors.horizontalCenter: appicon.horizontalCenter
                        antialiasing: true
                        color: "#1890FF"
                        Component.onCompleted: {
                            rightmask.visible = listview.count > 15 ? true : false
                        }
                    }
                }
            }
        }

        Image {
            id: rightmask
            source: "qrc:/ui/images/taskbar-rightmask.svg"
            anchors.verticalCenter: listview.verticalCenter
            anchors.right: listview.right
            visible: false
        }
        Image {
            id: leftmask
            source: "qrc:/ui/images/taskbar-leftmask.svg"
            anchors.left: listview.left
            anchors.verticalCenter: listview.verticalCenter
            visible: false
        }

        Rectangle {
            id: trayBack
            width: 72 * Style.tabletScaleFactor
            height: 64 * Style.tabletScaleFactor
            color: StylePrivate.StyleHelper.windowtextcolorrole
            opacity: trayMousearea.pressed ? 0.15 : 0.05
            anchors.right: taskbarBackground.right
            anchors.rightMargin: 16 * Style.tabletScaleFactor;
            anchors.verticalCenter: taskbarBackground.verticalCenter
            layer.enabled: true
            layer.effect: OpacityMask {
                maskSource: Rectangle {
                    width: trayBack.width
                    height: trayBack.height
                    radius: 14 * Style.tabletScaleFactor
                    Rectangle {
                        width: 30 * Style.tabletScaleFactor
                        height: trayBack.height
                        anchors.left: parent.left
                    }
                }
            }
            MouseArea {
                id: trayMousearea
                anchors.fill: parent
                onPressed: sidebarState.setSidebarShow()
            }
        }
        Rectangle {
            id: separator
            width: 1 * Style.tabletScaleFactor
            height: 32 * Style.tabletScaleFactor
            color: StylePrivate.StyleHelper.windowtextcolorrole
            opacity: 0.1
            anchors.right: trayBack.left
            anchors.verticalCenter: taskbarBackground.verticalCenter
        }
        Rectangle {
            id: timerBack
            width: 72 * Style.tabletScaleFactor
            height: 64 * Style.tabletScaleFactor
            color: StylePrivate.StyleHelper.windowtextcolorrole
            opacity: timeMousearea.pressed ? 0.15 : 0.05
            anchors.right: trayBack.left
            anchors.verticalCenter: taskbarBackground.verticalCenter
            layer.enabled: openGLEnabled
            layer.effect: OpacityMask {
                maskSource: Rectangle {
                    width: trayBack.width
                    height: trayBack.height
                    radius: 14 * Style.tabletScaleFactor
                    Rectangle {
                        width: 30 * Style.tabletScaleFactor
                        height: trayBack.height
                        anchors.right: parent.right
                    }
                }
            }
            MouseArea {
                id: timeMousearea
                anchors.fill: parent
                onPressed: showCal.showItem()
            }            
        }

        TimeComponent {
            id: timer
            anchors.centerIn: timerBack
        }

        StylePrivate.KyIcon {
            id: net
            width: 21 * Style.tabletScaleFactor
            height: 21 * Style.tabletScaleFactor
            anchors.top: trayBack.top
            anchors.topMargin: 11 * Style.tabletScaleFactor
            anchors.left: trayBack.left
            anchors.leftMargin: 12 * Style.tabletScaleFactor
            iconName: netWatcher.iconSource
            icontype: "filledSymbolicColor"
            TrayIconWatcher {
                id: netWatcher
                type: TrayIconWatcher.Network
            }
        }

        StylePrivate.KyIcon {
            id: bluetooth
            width: 21 * Style.tabletScaleFactor
            height: 21 * Style.tabletScaleFactor
            anchors.left: net.right
            anchors.leftMargin: 6 * Style.tabletScaleFactor
            anchors.verticalCenter: net.verticalCenter
            iconName: bluetoothWatcher.iconSource
            TrayIconWatcher {
                id: bluetoothWatcher
                type: TrayIconWatcher.Bluetooth
            }
        }

        StylePrivate.KyIcon {
            id: power
            width: 21 * Style.tabletScaleFactor
            height: 21 * Style.tabletScaleFactor
            anchors.top: net.bottom
            anchors.topMargin: 6 * Style.tabletScaleFactor
            anchors.horizontalCenter: net.horizontalCenter
            iconName: powerWatcher.iconSource
            icontype: "filledSymbolicColor"
            TrayIconWatcher {
                id: powerWatcher
                type: TrayIconWatcher.Power
            }
        }

        StylePrivate.KyIcon {
            id: sound
            width: 21 * Style.tabletScaleFactor
            height: 21 * Style.tabletScaleFactor
            anchors.horizontalCenter: bluetooth.horizontalCenter
            anchors.verticalCenter: power.verticalCenter
            iconName: volumeWatcher.iconSource
            TrayIconWatcher {
                id: volumeWatcher
                type: TrayIconWatcher.Volume
            }
        }
    }
}
